//
//  ILGDevice.m
//  ILGLibrary
//
//  Created by Happy on 8/27/16.
//  Copyright © 2016 Happy. All rights reserved.
//

#import "ILGDevice.h"

#import <AdSupport/AdSupport.h> //获取广告标示符的支持框架
#import <sys/utsname.h> //获取设备类型必备
#import <AudioToolbox/AudioToolbox.h> //手机振动需要

#import "ILGLocalData.h"
//#import "LGReachability.h"

// --- 获取ip需要 ---
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <net/if.h>

@interface ILGDevice () <UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
    
    
}
@property (nonatomic, copy) ImagePickerCallBack imagePickerCallback;
@end

@implementation ILGDevice

+ (instancetype)sharedInstance {
    static ILGDevice *manager = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        manager = [[ILGDevice alloc] init];
    });
    
    return manager;
}

- (void)fetchImageFromSystem:(int)sourceType viewController:(UIViewController *)vc callback:
(ImagePickerCallBack)callback {
    UIImagePickerControllerSourceType pickerSourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    if (sourceType == 1) {
        pickerSourceType = UIImagePickerControllerSourceTypeCamera;
    }
    _imagePickerCallback = callback;
    
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = pickerSourceType;
    
    vc ? nil:(vc = [UIApplication sharedApplication].keyWindow.rootViewController);
    [vc presentViewController:picker animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *chooseImage = info[UIImagePickerControllerEditedImage];
    
    __weak typeof(self) weakSelf = self;
    [picker dismissViewControllerAnimated:YES completion:^{
        weakSelf.imagePickerCallback(chooseImage);

    }];
}


+ (NSString *)deviceUUIDString {
    NSString *uuid = [ILGLocalData keyChainObject:ZCDeviceInfo_Key_UUID];
    if (!uuid) {
        uuid = [[UIDevice currentDevice] identifierForVendor].UUIDString;
        [ILGLocalData keyChainSave:uuid account:ZCDeviceInfo_Key_UUID];
    }
    return uuid;
}

+ (NSString *)advertisingIdentifier {
    NSString *idfa = [ILGLocalData keyChainObject:ZCDeviceInfo_Key_IDFA];
    if (!idfa) {
        idfa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
        [ILGLocalData keyChainSave:idfa account:ZCDeviceInfo_Key_IDFA];
    }
    return idfa;
}

+ (NSString *)deviceBrand {
    NSString *deviceType = [self deviceModel];
    
    if ([deviceType hasPrefix:@"iPhone"]) {
        return @"iPhone";
    } else if ([deviceType hasPrefix:@"iPod"]) {
        return @"iPod";
    } else if ([deviceType hasPrefix:@"iPad mini"]) {
        return @"iPad mini";
    } else  if ([deviceType hasPrefix:@"iPad air"]) {
        return @"iPad air";
    } else if ([deviceType hasPrefix:@"iPad"]) {
        return @"iPad";
    } else {
        return deviceType;
    }
}
+ (NSString *)deviceModel {
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"DeviceModel" ofType:@"plist"];
    NSDictionary *dataDic = [[NSDictionary alloc] initWithContentsOfFile:filePath];
    
    if (dataDic[deviceString]) {
        return dataDic[deviceString];
    } else {
        return deviceString;
    }
}

+ (void)audioServicesPlaySystemSoundWithCompletion:(void (^)(void))callback {
    AudioServicesPlayAlertSoundWithCompletion(kSystemSoundID_Vibrate, ^{
        callback ? callback():nil;
    });

}

// 获取外网ip地址
+ (NSString *)getWANIPAddress  {
    NSURL *ipURL = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"];
    NSData *data = [NSData dataWithContentsOfURL:ipURL];
    NSDictionary *ipDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSString *ipStr = nil;
    if (ipDic && [ipDic[@"code"] integerValue] == 0) { //获取成功
        ipStr = ipDic[@"data"][@"ip"];
    }
    return (ipStr ? ipStr : @"");
}


// 获取局域网ip地址
#define IOS_CELLULAR    @"pdp_ip0"
#define IOS_WIFI        @"en0"
//#define IOS_VPN       @"utun0"
#define IP_ADDR_IPv4    @"ipv4"
#define IP_ADDR_IPv6    @"ipv6"
+ (NSString *)getLANIPAddress:(BOOL)preferIPv4
{
    NSArray *searchArray = preferIPv4 ?
    @[ /*IOS_VPN @"/" IP_ADDR_IPv4, IOS_VPN @"/" IP_ADDR_IPv6,*/ IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :
    @[ /*IOS_VPN @"/" IP_ADDR_IPv6, IOS_VPN @"/" IP_ADDR_IPv4,*/ IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;
    
    NSDictionary *addresses = [self getIPAddresses];
    NSLog(@"addresses: %@", addresses);
    
    __block NSString *address;
    [searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
     {
         address = addresses[key];
         if(address) *stop = YES;
     } ];
    return address ? address : @"0.0.0.0";
}
//获取所有相关IP信息
+ (NSDictionary *)getIPAddresses
{
    NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
    
    // retrieve the current interfaces - returns 0 on success
    struct ifaddrs *interfaces;
    if(!getifaddrs(&interfaces)) {
        // Loop through linked list of interfaces
        struct ifaddrs *interface;
        for(interface=interfaces; interface; interface=interface->ifa_next) {
            if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
                continue; // deeply nested code harder to read
            }
            const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
            char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
            if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
                NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
                NSString *type;
                if(addr->sin_family == AF_INET) {
                    if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv4;
                    }
                } else {
                    const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
                    if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv6;
                    }
                }
                if(type) {
                    NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
                    addresses[key] = [NSString stringWithUTF8String:addrBuf];
                }
            }
        }
        // Free memory
        freeifaddrs(interfaces);
    }
    return [addresses count] ? addresses : nil;
}
@end
